import * as api from '@/services/checkTask';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Checkbox, Collapse, Divider, Popconfirm, Space, Tag, message } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import CheckReportForm from './CheckReportForm';
import CheckDomainForm from './CheckDomainForm';
import CheckManualForm from './CheckManualForm';
import RecheckServerForm from './RecheckForm';
import RecheckDomainForm from './RecheckDomainForm';
import RecheckManualForm from './RecheckManualForm';
import * as utils from '@/utils/utils';
import * as c from '@/services/consts';
import Countdown from 'antd/es/statistic/Countdown';
import { ClockCircleOutlined, RedoOutlined, UserOutlined } from '@ant-design/icons';
const { Panel } = Collapse;
import CheckTaskStatusTag from '@/components/CheckTaskStatusTag';

const OrderList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const [formCheckReportVisible, setFormCheckReportVisible] =useState<boolean>(false);
  const [formCheckDomainVisible, setFormCheckDomainVisible] =useState<boolean>(false);
  const [formCheckManualVisible, setFormCheckManualVisible] =useState<boolean>(false);
  const [formRecheckServerVisible, setFormRecheckServerVisible] =useState<boolean>(false);
  const [formRecheckDomainVisible, setFormRecheckDomainVisible] =useState<boolean>(false);
  const [formRecheckCustomVisible, setFormRecheckCustomVisible] =useState<boolean>(false);
  const [currentVer, setCurrentVer] = useState<string | undefined>(undefined);
  const [countdownTicks, setCountdownTicks] = useState<number>(Date.now() + 60000,);
  const [listType, setListType] = useState<string>('all');
  const [displayAutoTask, setDisplayAutoTask] =useState<boolean>(false);
  const [currentTask, setCurrentTask] = useState<API.CheckTask | undefined>(undefined);
  // const [selectIds, setSelectIds] = useState<any[]>([]);
  
  const { getSupplier,getVpnGroupOptions } = useModel('useGlobalModel', (model) => ({
    getSupplier: model.getSupplier,
    getVpnGroupOptions: model.getVpnGroupOptions,
  }));
  
  // const handleRecheckSubmit = async (ver: string | undefined) => {
  //   const result = await api.create({recheckId: ver});
  //   if (result && result.success) {
  //     actionRef?.current?.reload();
  //   }
  // };
  
  const handleCheckDomainSubmit = async () => {
    setFormCheckDomainVisible(false);
    actionRef?.current?.reload();
  };
  
  const handleCheckManualSubmit = async () => {
    setFormCheckManualVisible(false);
    actionRef?.current?.reload();
  };

  const handleRemove = async (ver: string | undefined) => {
    const result = await api.remove({ver});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      reload();
    }
  };

  const handleRemoves = async (ids:any[]) => {
    const result = await api.removes({vers:ids});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      reload();
    }
  };
    
  const reload = () => {
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + 60000);
  };

  let columns: ProColumns<API.CheckTask>[] = [
    {
      title: '版本',
      dataIndex: 'id',
      width: 200,
      sorter: true,
      render: (_, record) => {
        return (
          <>
          <div style={{marginBottom:5}}>
          <CheckTaskStatusTag status={record.status} />
          </div>
          <Tag color={utils.getTextRanColor(record.job)}>{c.getObjectText(c.CheckJobAllOptions, record.job)}</Tag>
          {/* {record.mode ? <Tag color={utils.getTextRanColor(record.mode)}>{c.getObjectText(c.CheckModeOptions, record.mode)}</Tag> : ''} */}
          <div>{record.id}</div>
          {record.scheduleId ? <div><RedoOutlined />{record.schedulePublishId}<br />{record.scheduleId}</div> : ''}
          {record.createUser ? <div style={{color:'#aaa'}}><UserOutlined /> {record.createUser}</div> : ''}
          {record.createTime ? <div style={{color:'#aaa'}}><ClockCircleOutlined /> {utils.formatDate(record.createTime)}</div> : ''}
          </>
        );
      },
    },
    
    {
      title: '检测内容',
      dataIndex: 'instanceIds',
      search: false,
      sorter: true,
      render: (_, record) => {
        return <>
        {record.schedule ? <><div><Tag color="blue">定时检测间隔：{record.schedule?.interval}分钟</Tag></div></> : ''}
        {record.serverIds ? <div style={{marginBottom:10}}><h4>检测服务器</h4>
          {record.serverIds.map((sid)=>{
          let ser = record.progresss?.filter((el)=>el.serverId == sid);
          return ser && ser.length > 0 
            ? <Tag color={ser[0].percent == 100 ? 'green' : ser[0].percent >= 0 ? 'blue' : ''}>{ser[0].serverId} {ser[0].percent}%</Tag>
            : <><Tag>{sid}</Tag></>        
        })}</div> : ''}
        
        <Collapse style={{marginBottom:10}} defaultActiveKey={['33']} ghost size='small'><Panel key="33" header={<>
        {record.name ? <span style={{color:record.scheduleId ? '#f50' : '#D48806'}}><b>检测：{record.name}</b></span> : <b>检测内容</b>}
          {/* {record.remark ? <span style={{color:'#999'}}> {record.remark}</span> : ''} */}
        {record.remark || record.parentId ? <span style={{color:'#999'}}> {record.remark}{record.parentId ? ` [P:${record.parentId}]` : ''}</span> : ''}
          </>}>
        {/* {record.templetNames && record.templetNames.length > 0 ? <div style={{marginBottom:10}}><h4>检测模板</h4>
          {record.templetNames.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''} */}

        {record.groupNames && record.groupNames.length > 0 ? <div style={{marginBottom:10}}><h4>检测分组</h4>
          {record.groupNames.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}

        {record.instanceIds && record.instanceIds.length > 0 ? <div style={{marginBottom:10}}><h4>检测节点</h4>
          {record.instanceIds.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}

        {record.supplierIds && record.supplierIds.length > 0 ? <div style={{marginBottom:10}}><h4>服务器提供商</h4>
          {record.supplierIds.map((sid)=>{
          return <Tag color="blue">{getSupplier(sid)?.name}</Tag>
        })}</div> : ''}

        {record.customs && record.customs.length > 0 ? <div style={{marginBottom:10}}><h4>自定义检测</h4>
          {record.customs.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}
        
        </Panel></Collapse>
        </>
      },
    },
    
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'single',
        allowClear: true,
        showSearch: true,
        options: c.CheckTaskStatusOptions,
      },
    },
    {
      title: '自定义名称',
      dataIndex: 'name',
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '分组',
      dataIndex: 'groupId',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'single',
        allowClear: true,
        showSearch: true,
        options: getVpnGroupOptions(undefined),
      },
    },

  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 210,
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('checktask_delete')) {
          cmps.push(
            <Popconfirm
              key="check_delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        // if (hasRight('checktask_create')) {
        //   cmps.push(
        //     <Popconfirm
        //       key="check_recheck"
        //       title="确定要重新检测吗?"
        //       onConfirm={async () => {
        //         await handleRecheckSubmit(record.id);
        //       }}
        //     >
        //       <a>重新检测</a>
        //     </Popconfirm>,
        //   );
        // }
        if (hasRight('checktask_create')) {
          cmps.push(
            <a
              key="check_recheck"
              onClick={() => {
                if(record.job == c.CheckJob.CheckApi.value){
                  setFormRecheckDomainVisible(true);
                }
                else if(record.customs?.length > 0){
                  setFormRecheckCustomVisible(true);
                }
                else{
                  setFormRecheckServerVisible(true);
                }
                setCurrentTask(record);
              }}
            >
              重新检测
            </a>,
          );
        }

        if (hasRight('checktask_list')) {
          cmps.push(
            <a
              target="_blank"
              key="excel"
              href={`/admin-api/checktask/export?ver=${record.id}`}
            >
              下载
            </a>
          );


          cmps.push(
            <a
              key="check_report"
              onClick={() => {
                setCurrentVer(record.id);
                setFormCheckReportVisible(true);
              }}
            >
              检测结果
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        search={{
          defaultCollapsed: false,
          span: 4,
        }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          toolbarDoms.push([              
            <Checkbox
              checked={displayAutoTask}
              onChange={(e) => {
                setDisplayAutoTask(e.target.checked);
              }}
            >
              <span style={{color:'red', fontWeight:'bold'}}>  
                仅自动检测
              </span>
            </Checkbox>
          ]);

          if (hasRight('checktask_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create_check_manual"
                onClick={() => {
                  setFormCheckManualVisible(true);
                }}
              >
               自定义检测
              </Button>
            ]);
          }

          if (hasRight('checktask_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create_check_domain"
                onClick={() => {
                  setFormCheckDomainVisible(true);
                }}
              >
               域名检测
              </Button>
            ]);
          }

          
          // if (hasRight('checktask_update')) {
          //   toolbarDoms.push([
          //     <Button
          //       type="primary"
          //       danger
          //       key="checktask_publish"
          //       onClick={async() => {
          //         await handlePublish(undefined);
          //       }}
          //     >
          //      下发配置
          //     </Button>
          //   ]);
          // }

          toolbarDoms.push([
            <span>
            <Countdown
              title=""
              key="cdRefresh"
              value={countdownTicks}
              format="s"
              prefix=""
              suffix="秒后刷新"
              valueStyle={{
                fontSize: 14,
                color: 'gray',
              }}
              onFinish={reload}
            />
          </span>
          ]);

          return toolbarDoms;
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: listType,
            items: [
              {label: '全部',key: 'all'},
              {label: '无名称',key: 'unname'},
              {label: '自定义名称',key: 'customname'},
              // {label: '非自动检测',key: 'unauto'},
              // {label: '自动检测',key: 'auto'},
            ],//,{label: '检测中',key: 'checking'}
            onChange: (tabKey) => {
              setListType(tabKey as string);
            },
          },
        }}
        rowSelection={{
          defaultSelectedRowKeys: [],
          // onChange: (selectedRowKeys, selectedRows) => {
          //   setSelectIds(selectedRowKeys);
          // },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
            

            <span>
              {hasRight('checktask_delete') ?
                  <Popconfirm
                    key="check_delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemoves(selectedRowKeys);
                    }}
                  >
                    <a>删除</a>
                  </Popconfirm>
                : ''
              }
            </span>
          </Space>
        )}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
        }}
        params={{
          listType: listType,
          displayAutoTask: displayAutoTask,
        }}
        request={api.list}
      />
      <CheckReportForm
        visible={formCheckReportVisible}
        ver={currentVer}
        groupId={undefined}
        onCancel={() => {
          setFormCheckReportVisible(false);
        }}
        onCancelAndReload={() => {
          setFormCheckReportVisible(false);
          actionRef.current?.reload();
        }}
      />
      <CheckDomainForm
        visible={formCheckDomainVisible}
        onCancel={() => {
          setFormCheckDomainVisible(false);
        }}
        onSubmit={handleCheckDomainSubmit}
      />
      <CheckManualForm
        visible={formCheckManualVisible}
        onCancel={() => {
          setFormCheckManualVisible(false);
        }}
        onSubmit={handleCheckManualSubmit}
      />
      <RecheckServerForm
        visible={formRecheckServerVisible}
        currentTask={currentTask}
        onCancel={() => {
          setFormRecheckServerVisible(false);
          setCurrentTask(undefined);
        }}
        onSubmit={() => {
          setFormRecheckServerVisible(false);
          setCurrentTask(undefined);
          actionRef.current?.reload();
        }}
      />
      <RecheckDomainForm
        visible={formRecheckDomainVisible}
        currentTask={currentTask}
        onCancel={() => {
          setFormRecheckDomainVisible(false);
          setCurrentTask(undefined);
        }}
        onSubmit={() => {
          setFormRecheckDomainVisible(false);
          setCurrentTask(undefined);
          actionRef.current?.reload();
        }}
      />
      <RecheckManualForm
        visible={formRecheckCustomVisible}
        currentTask={currentTask}
        onCancel={() => {
          setFormRecheckCustomVisible(false);
          setCurrentTask(undefined);
        }}
        onSubmit={() => {
          setFormRecheckCustomVisible(false);
          setCurrentTask(undefined);
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default OrderList;
